package com.gzhu.knowledgeAdmin.common.utils;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzhu.knowledgeAdmin.common.result.R;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ResponseUtil {

    public static void out(HttpServletResponse response, R r) {
        ObjectMapper mapper = new ObjectMapper();
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            mapper.writeValue(response.getWriter(), r);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void writeStreamData(ServletOutputStream outputStream, InputStream inputStream){
        BufferedInputStream bin = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] resultByte = null;
        try {

            // 从请求中获取数据
            bin = new BufferedInputStream(inputStream);
            byte[] bytes = new byte[1024 * 4];
            int n = 0;
            while (-1 != (n = bin.read(bytes))) {
                bos.write(bytes, 0, n);
            }
            resultByte = bos.toByteArray();
            outputStream.write(resultByte);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bin != null) {
                    bin.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
